<?php
namespace App\Model\Backstage;
use App\Model\Base;
use Illuminate\Support\Facades\DB;
use App\Model\Backstage\Achievement;

/**
 * Class RoomInfo
 * @package App\Model\Backstage
 * 房源信息model
 */
class RoomInfo extends Base
{
    protected $table;
    protected $achievement_model;
    protected $achievement_table;
    protected $customers_table;
    protected $follow_table;
    protected $source_table;
    protected $comm_disk = 106;  //公盘对应ID
    protected $private_disk = 107; //私盘对应ID
    protected $excellent_room = 101; //优质房对应ID
    protected $ordinary_room = 100;  //普通房对应ID
    public  function __construct()
    {
        parent::__construct();
       // $this->table = 'room_info_'.$this->branch_id;
        $this->table = 'room_info';

        $this->achievement_model = new Achievement();
        $this->achievement_table = 'achievement';  //后期需要分公司表
        $this->customers_table = 'customers'; //后期需要分公司表
        $this->follow_table = 'follow';
        $this->source_table = 'customer_follow_source';
    }

     public  function getRoomInfoList ()
    {
       DB::table($this->table)->where();
    }

    /*
     * 验证房源重复
     * Wu Ning
     */
    public function verificationRoomRepeat($params){
        $list = DB::table($this->table)
            ->where('a_id',$params['a_id'])//区县id
            ->where('building_id',$params['building_id'])//楼盘字典id
            ->where('few_building',$params['few_building'])//几号楼
            ->where('room_number',$params['room_number'])//房号
            ->first();
        if(sizeof($list) == 0) {
            return true;
        }else{
            return false;
        }

    }


    /*
     * 添加房源信息
     * Wu Ning
     */
    public  function addRoomInfo($params)
    {
//        DB::beginTransaction();
        $params['r_created_at'] = time();//创建时间，时间戳
        $params['r_entrust_at'] = time(); //委托时间 首次录入时委托时间默认为当前时间
        $params['company_id'] = $this->branch_id; //公司ID自动获取
        return DB::table($this->table)->insertGetId(
            $params
//            [
//            'p_id'                  =>  $params['p_id'],
//            'c_id'                  =>  $params['c_id'],
//            'a_id'                  =>  $params['a_id'],
//            'building_id'           =>  $params['building_id'],
//            'few_building'          =>  $params['few_building'],
//            'room_number'           =>  $params['room_number'],
//            'floor'                 =>  $params['floor'],
//            'total_layer'           =>  $params['total_layer'],
//            'use_type'              =>  $params['use_type'],
//            'housing_types'         =>  $params['housing_types'],
//            'type_of_house_sale'    =>  $params['type_of_house_sale'],
//            'building_s'            =>  $params['building_s'],
//            'disc_type'             =>  $params['disc_type'],
//            'trading_type'          =>  $params['trading_type'],
//            'trading_state_type'    => $params['trading_state_type'],
//            'price'                 => $params['price'],
//            'unit_price'            => $params['unit_price'],
//            'sale_floor_price'      => $params['sale_floor_price'],
//            'floor_price'           => $params['floor_price'],
//            'rents_unit_price'      => $params['rents_unit_price'],
//            'taxes_fees'            => $params['taxes_fees'],
//            'rents'                 => $params['rents'],
//            'rents_type'            => $params['rents_type'],
//            'entrust_way'           => $params['entrust_way'],
//            'admin_cost'            => $params['admin_cost'],
//            'making_room'           => $params['making_room'],
//            'entrust_number'        => $params['entrust_number'],
//            'source_type'           => $params['source_type'],
//            'status_quo'            => $params['status_quo'],
//            'decoration'            => $params['decoration'],
//            'support'               => $params['support'],
//            'furniture'             => $params['furniture'],
//            'appliance'             => $params['appliance'],
//            'rights_type'           => $params['rights_type'],
//            'certificate_type'      => $params['certificate_type'],
//            'payment_type'          => $params['payment_type'],
//            'pay_on_type'           => $params['pay_on_type'],
//            'checking_way'          => $params['checking_way'],
//            'checking_remark'       => $params['checking_remark'],
//            'contact_name'          => $params['contact_name'],
//            'contact_phone'         => $params['contact_phone'],
//            'remark'                => $params['remark'],
//            'owner_name'            =>  $params['owner_name'],
//            'owner_phone'           =>  $params['owner_phone'],
//            'r_d_id'                => $this->store_id,
//            'source_uid'            => $this->uid
//
//        ]
        );
        //$params['p_id'],$params['c_id'],$params['a_id'],
        //$params['building_id'],$params['few_building'],$params['room_number']


//        if($cid){
//            DB::commit();
//            return true;
//        } else {
//            DB::rollback();
//            return false;
//        }
    }

    /*
     * 修改房源
     */
    public function updataHouse($params)
    {
        $params['company_id'] = $this->branch_id; //公司ID自动获取
        $params['r_updated_at'] = time();   //修改时间
        $status = DB::table($this->table)->where('id',$params['id'])->value('status');
        //如果房源从其他状态改为有效的时候更新委托时间
        //此处状态值后期需要校验修正91
        if($status != 91 && $params['status'] == 91){
            $params['r_entrust_at'] = time();
        }
        return DB::table($this->table)
            ->where('id', $params['id'])
            ->update(
                $params
//                [
//                'p_id'                  =>  $params['p_id'],
//                'c_id'                  =>  $params['c_id'],
//                'a_id'                  =>  $params['a_id'],
//                'building_id'           =>  $params['building_id'],
//                'few_building'          =>  $params['few_building'],
//                'room_number'           =>  $params['room_number'],
//                'floor'                 =>  $params['floor'],
//                'total_layer'           =>  $params['total_layer'],
//                'use_type'              =>  $params['use_type'],
//                'housing_types'         =>  $params['housing_types'],
//                'type_of_house_sale'    =>  $params['type_of_house_sale'],
//                'building_s'            =>  $params['building_s'],
//                'disc_type'             =>  $params['disc_type'],
//                'trading_type'          =>  $params['trading_type'],
//                'trading_state_type'    => $params['trading_state_type'],
//                'price'                 => $params['price'],
//                'unit_price'            => $params['unit_price'],
//                'sale_floor_price'      => $params['sale_floor_price'],
//                'floor_price'           => $params['floor_price'],
//                'rents_unit_price'      => $params['rents_unit_price'],
//                'taxes_fees'            => $params['taxes_fees'],
//                'rents'                 => $params['rents'],
//                'rents_type'            => $params['rents_type'],
//                'entrust_way'           => $params['entrust_way'],
//                'admin_cost'            => $params['admin_cost'],
//                'making_room'           => $params['making_room'],
//                'entrust_number'        => $params['entrust_number'],
//                'source_type'           => $params['source_type'],
//                'status_quo'            => $params['status_quo'],
//                'decoration'            => $params['decoration'],
//                'support'               => $params['support'],
//                'furniture'             => $params['furniture'],
//                'appliance'             => $params['appliance'],
//                'rights_type'           => $params['rights_type'],
//                'certificate_type'      => $params['certificate_type'],
//                'payment_type'          => $params['payment_type'],
//                'pay_on_type'           => $params['pay_on_type'],
//                'checking_way'          => $params['checking_way'],
//                'checking_remark'       => $params['checking_remark'],
//                'contact_name'          => $params['contact_name'],
//                'contact_phone'         => $params['contact_phone'],
//                'remark'                => $params['remark'],
//                'created_at'            =>  time(),//创建时间，时间戳
//                'owner_name'            =>  $params['owner_name'],
//                'owner_phone'           =>  $params['owner_phone'],
//                'room_status'           =>  '1',//房源状态 1正常 2回收站，
//
//                'source_uid'            =>  '34'//录入员工id--34
//            ]
            );
    }

    /*
     * 房源列表
     * Wu Ning
     */
    public function listRoom($pageLimit, $where = [], $keywords){
        $field = ['id', 'property_number', 'a_id','building_id','few_building','rents_type','rents','room_number','floor','total_layer','use_type',
            'housing_types','type_of_house_sale','building_s','disc_type','trading_type','trading_state_type',
            'price','unit_price','sale_floor_price','floor_price','rents_unit_price','taxes_fees',
            'entrust_way','admin_cost','making_room','entrust_number','source_type','status_quo',
            'rights_type','payment_type','pay_on_type','decoration','support','furniture','appliance',
            'certificate_type','checking_way','checking_remark','remark','r_d_id','source_uid',
            'owner_name','owner_phone','contact_name','contact_phone','room_status','source_uid','status',
            DB::raw('from_unixtime(r_created_at) as r_created_at'), DB::raw('from_unixtime(r_updated_at) as r_updated_at'),'r_acreage', 'r_info', 'status',
            'r_detaile_list',
            'u_id','u_username','u_account_number','u_type',
        ];
        if ($keywords == '' ) {
            $list = DB::table($this->table)
                ->leftjoin('user', 'source_uid', '=', 'u_id')
                ->where($where)
                ->select($field)
                ->orderBy('id', 'desc')
                ->paginate($pageLimit);
        }else {
            $list = DB::table($this->table)
                ->leftjoin('user', 'source_uid', '=', 'u_id')
                ->where(function ($query) use($where, $keywords){
                    $query->where($where)->where('owner_name', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords) {
                    $query->where($where)->where('owner_phone', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where($where)->where('contact_name', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where($where)->where('contact_phone', 'like', '%'.$keywords.'%');
                })
                ->select($field)
                ->orderBy('id', 'desc')
                ->paginate($pageLimit);
        }

        if (sizeof($list) == 0) {
            return false;
        }
        return $list;
    }
    /*
     *软删除房源
     */
    public function softDelHouse($id)
    {
        return DB::table($this->table)->where('id', $id)->update(['room_status' => 2]);
    }

    /*
     * 永久删除房源 和房源跟进 和房源提醒
     *<中介公司 看不到该信息>
     */
    public function DelHouse($id)
    {
        //李向阳- 此处不建议开启事务 因为牵扯录入房源后没有添加跟进或者未添加提醒，
        //所以会导致删除失败，事务回滚
        //开启事务
//        DB::beginTransaction();
        $RelHouse =  DB::table($this->table)->where('id', $id)->update(['room_status' => 3]);
        $RelFollow =  DB::table($this->follow_table)->where('f_room_id', $id)->delete();
        $RelRemind = DB::table($this->source_table)->where(['cfs_type'=>1,'cfs_type_id'=>$id])->delete();
        if($RelHouse){
//            DB::commit();
            return true;
        }
//        DB::rollback();
        return false;
    }

    /**
     * 修改房源状态信息，增加员工业绩计算
     * 房源状态(1有效 2预定 3已售 4已租 5我售 6我租 7暂缓 8未知 9无效)
     */
    public function saveRoomStatus($param){
        //此处状态值后期需要校验修正
        if($param['status'] == 5 || $param['status'] == 6){  //判断是否为我租或者我售

            $res = DB::table($this->achievement_table)->where(['a_room_id' => $param['room_id'],'a_customer_id' => $param['customer_id']])->first();
            if($res){
                return ['code' => 0,'msg' => '该房源已经分配过业绩'];
            }
            //开启事务
            DB::beginTransaction();
            try
            {
                DB::table($this->table)->where('id', $param['room_id'])->update(['status' => $param['status']]);
                DB::table($this->customers_table)->where('c_id' , $param['customer_id'])->update(['c_buy_status' => $param['status']]);


                if($param['type'] == 1){  //独立完成订单
                    $data['a_uid'] = $this->uid;
                    $data['a_room_id'] = $param['room_id'];
                    $data['a_customer_id'] = $param['customer_id'];
                    $data['a_ubid'] = $this->store_id;
                    $data['a_money'] = $param['money'];
                    $data['a_created_at'] = time();
                    $data['a_remark'] = $param['remark'];
                }else{  //多人配合
                    $data = [];
//                    $rate_arr = explode(',' , $param['rate']);
//                    $user_id = explode(',' , $param['u_id']);
                    $rate_arr = $param['rate'];
                    $user_id = $param['u_id'];
                    $rate = array_sum($rate_arr);
                    if($rate != 10){
                        return ['code' => 0, 'msg' => '分成设置错误'];
                    }
                    foreach($user_id as $k => $v){
                        $data[$k]['a_uid'] = $v;
                        $data[$k]['a_room_id'] = $param['room_id'];
                        $data[$k]['a_customer_id'] = $param['customer_id'];
                        $data[$k]['a_ubid'] = $this->store_id;
                        $data[$k]['a_money'] = sprintf("%.2f",substr(sprintf("%.3f", $rate_arr[$k] / $rate * $param['money'] ), 0, -2));
                        $data[$k]['a_created_at'] = time();
                        $data[$k]['a_remark'] = $param['remark'];
                    }
                }
                DB::table($this->achievement_table)->insert($data);
                DB::commit();
                return ['code' => 1, 'msg' => '添加成功'];
            }
            catch(Exception $e)
            {
                DB::rollback();
                return ['code' => 2, 'msg' => '添加失败'];
            }
        }else{    //否则不处理业绩问题，直接修改房源状态

            $status = DB::table($this->table)->where('id',$param['room_id'])->value('status');
            //如果房源从其他状态改为有效的时候更新委托时间
            //此处状态值后期需要校验修正91
            if($status != 91 && $param['status'] == 91){
                $param['r_entrust_at'] = time();
            }
            $param['r_updated_at'] = time();
            $res = DB::table($this->table)->where('id',$param['room_id'])->update(['status'=>$param['status']]);
            if($res){
                return ['code' => 1, 'msg' => '修改成功'];
            }else{
                return ['code' => 2, 'msg' => '修改失败'];
            }
        }
    }


    /**
     * @param array $map
     * @param $pageLimit
     * @return mixed
     * 获取员工房源录入数量排行
     */
    public function roomAchievementList($map = [],$pageLimit){
        $where = [
            'u_b_id' => $this->branch_id,
            'is_del' => 0,
            'u_status' => 1
        ];
        $user_list = DB::table('user')
            ->where($where)
            ->select(['u_id','u_username','u_type'])
            ->get()
            ->toArray();
        foreach($user_list as $k => $v){
            $num = DB::table($this->table)->where($map)->where('source_uid', $v->u_id)->count();
            $v->num = $num;
        }
        $list = json_encode($user_list);
        $list = json_decode($list,true);
        array_multisort(array_column($list,'num'),SORT_DESC,$list);
        return $list;
    }


    /**
     * @param $id
     * @return mixed
     * 根据房源ID获取房源详细信息
     */
    public function getRoomInfo($id){
        return DB::table($this->table)->where('id', $id)->first();
    }

    /**
     * 添加跟进记录时更新房源最后跟进时间
     */
    public function updateFollowTime($id){
        return DB::table($this->follow_table)->where('id', $id)->update(['r_follow_time' => time()]);
    }


    /**
     * @param $param
     * 更新公司自动转移规则对应的房源信息
     * 该方法可作为即时执行调用 参数为单条信息 时间类型输入除过判断外的类型值即可
     */
    public  function updateRuleDisk($param){
        $map = $this->dateMap($param);
        return $this->updateRoomDisk($map, $param, $param['a_move_type']);
    }

    /**
     * @param $param
     * @return array
     * 时间类型判断
     */
    public function dateMap($param){
        $map = [];
        $times = time() - 60 * 60 * 24 * $param['a_day_num'];
        switch($param['a_date_type']){   //判断查找时间类型
            case 0: //最后跟进日期
                $map[] = ['r_follow_time', '<=', $times];
                break;
            case 1: //委托日
                $map[] = ['r_entrust_at', '<=', $times];
                break;
            case 2:  //录入日
                $map[] = ['r_created_at', '<=', $times];
                break;
            default:
                break;
        }
        return $map;
    }

    /**
     * @param $map
     * @param $params
     * @return mixed
     * 更新房屋公私盘 取消优质房
     */
    public function updateRoomDisk($map, $params, $type){
        $map[] = ['r_d_id', $params['a_d_id']]; //部门ID
        //以下所有判断如果类型值为false则代表全部，不作为过滤条件
        if(isset($params['a_trade_type']) && $params['a_trade_type'] != ''){  //交易类型  出租 出售
            $map[] = ['trading_type', $params['a_trade_type']];
        }
        if(isset($params['a_m_status']) && $params['a_m_status'] != ''){   //房源状态 有效  无效 我租等
            $map[] = ['status', $params['a_m_status']];
        }
        if(isset($params['a_use_type']) && $params['a_use_type'] != ''){  //房源用途
            $map[] = ['use_type', $params['a_use_type']];
        }
        $update_data = [];
        if($type == 0){  //修改私盘到公盘
            $map[] = ['disc_type', $this->private_disk];     //查找对应条件所有私盘 私盘不包括 封盘 特盘
            $update_data = [
                'disc_type' => $this->comm_disk,
                'r_updated_at' => time()
            ];
        }elseif($type == 2){  //取消优质房
            $map[] = ['type_of_house_sale', $this->excellent_room];    //查询对应条件优质房进行修改
            $update_data = [
                'type_of_house_sale' => $this->ordinary_room,
                'r_updated_at'       => time()
            ];
        }
        if(isset($params['a_entrust_way']) && $params['a_entrust_way'] != ''){  //委托方式
            $entrust_arr = explode(',', $params['a_entrust_way']);
            return DB::table($this->table)
                ->where($map)
                ->whereIn('entrust_way',$entrust_arr)
                ->update($update_data);
        }else{
            return DB::table($this->table)->where($map)->update($update_data);
        }

    }

    /**
     * @param $param
     * @return mixed
     * 转移房源 或者跟进记录所属人
     * @param $type 1代表更新房源  2代表获取满足条件的房源
     */
    public function moves($param, $type){
        $map = $this->moveMap($param);
        if($type == 1 ){
            if($param['num'] > 0){  //如果转移数量大于0则按条件获取固定数量的数据
                $ids = DB::table($this->table)
                    ->where($map)
                    ->limit($param['num'])
                    ->orderBy('id', 'desc')
                    ->pluck('id');
                return DB::table($this->table)
                    ->whereIn('id',$ids)
                    ->update([
                        'r_d_id' => $param['to_d_id'],
                        'source_uid' => $param['to_uid'],
                        'r_updated_at' => time()
                    ]);
            }else{
                return DB::table($this->table)
                    ->where($map)
                    ->update([
                        'r_d_id' => $param['to_d_id'],
                        'source_uid' => $param['to_uid'],
                        'r_updated_at' => time()
                    ]);
            }

        }else{
            if($param['num'] > 0){  //如果转移数量大于0则按条件获取固定数量的数据
                return DB::table($this->table)
                    ->where($map)
                    ->limit($param['num'])
                    ->orderBy('id', 'desc')
                    ->pluck('id');
            }else{
                return DB::table($this->table)
                    ->where($map)
                    ->orderBy('id', 'desc')
                    ->pluck('id');
            }
        }
    }
    /**
     * @param $param
     * @return array
     * 判断条件
     */
    public function moveMap($param){
        $map[] = ['r_d_id', $param['out_d_id']];  //部门ID
        $map[] = ['source_uid', $param['out_uid']];  //用户ID
        $map[] = ['room_status', 1];
        if(isset($param['a_id']) && $param['a_id'] != ''){  //区code
            $map[] = ['a_id', $param['a_id']];
        }
        if(isset($param['w_id']) && $param['w_id'] != ''){  //楼盘字典ID
            $map[] = ['building_id', $param['w_id']];
        }
        if(isset($param['trading_type']) && $param['trading_type'] != ''){ //交易类型 出租 出售 租售
            $map[] = ['trading_type', $param['trading_type']];
        }
        if(isset($param['status']) && $param['status'] != ''){  //房源状态
            $map[] = ['status', $param['status']];
        }
        if(isset($param['start_time']) && $param['start_time'] != ''){ //开始时间
            $map[] = ['r_entrust_at', '>=', strtotime($param['start_time'])];
        }
        if(isset($param['end_time']) && $param['end_time'] != ''){  //结束时间
            $map[] = ['r_entrust_at', '<=', strtotime($param['end_time'])];
        }
        return $map;
    }

    /**
     * @param $params
     * @return mixed
     * 公私盘转移
     */
    public function turns($params){
        $map = $this->dateMap($params); //时间数组
        //部门
        if(isset($params['a_d_id']) && $params['a_d_id'] != ''){
            $map[] = ['r_d_id', $params['a_d_id']];
        }
        //员工
        if(isset($params['a_uid']) && $params['a_uid'] != ''){
            $map[] = ['source_uid', $params['a_uid']];
        }
        //区域
        if(isset($params['a_code']) && $params['a_code'] != ''){
            $map[] = ['a_id', $params['a_code']];
        }
        //交易类型
        if(isset($params['trading_type']) && $params['trading_type'] != ''){
            $map[] = ['trading_type', $params['trading_type']];
        }
        //状态
        if(isset($params['status']) && $params['status'] != ''){
            $map[] = ['status', $params['status']];
        }
        $updateData = [];
        if($params['turn_type'] == 0){   //私转公
            $map[] = ['disc_type', $this->private_disk];
            $updateData = [
                'disc_type' => $this->comm_disk,
                'r_updated_at' => time()
            ];
        } elseif($params['turn_type'] == 1){  //公转私
            $map[] = ['disc_type', $this->comm_disk];
            $updateData = [
                'disc_type' => $this->private_disk,
                'r_updated_at' => time()
            ];
        }
        return DB::table($this->table)
                ->where($map)
                ->update($updateData);
    }

    /**
     * 简单查找房源列表
     */
    public function listRoomFast($pageLimit, $where = [], $keywords){
        $field = ['id', 'property_number', 'entrust_number', 'a_id', 'trading_type', 'building_id', 'few_building', 'room_number',
            'r_acreage', 'status', DB::raw('from_unixtime(r_entrust_at) as r_entrust_at')];
        if ($keywords == '' ) {
            $list = DB::table($this->table)
                ->where($where)
                ->select($field)
                ->orderBy('id', 'desc')
                ->paginate($pageLimit);
        }else {
            $list = DB::table($this->table)
                ->where(function ($query) use($where, $keywords){
                    $query->where($where)->where('owner_name', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords) {
                    $query->where($where)->where('owner_phone', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where($where)->where('contact_name', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where($where)->where('contact_phone', 'like', '%'.$keywords.'%');
                })
                ->select($field)
                ->orderBy('id', 'desc')
                ->paginate($pageLimit);
        }

        if (sizeof($list) == 0) {
            return false;
        }
        return $list;
    }

}